package info.hexin.spring.annontion1.spring;

import info.hexin.spring.annontion1.annontion.RpcService;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * Created by infi.he on 2016/3/7.
 */
@Component
public class MyRpcBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        RpcService annotation = AnnotationUtils.findAnnotation(targetClass, RpcService.class);
        if (annotation != null) {
            ProxyFactory factory = new ProxyFactory(bean);
            factory.setProxyTargetClass(true);
            factory.addAdvice(new MethodInterceptor() {
                @Override
                public Object invoke(MethodInvocation invocation) throws Throwable {
                    Method method = invocation.getMethod();
                    System.out.println("before>>>>" + method);
                    Object proceed = null;
                    if (ReflectionUtils.isObjectMethod(method)) {
                        proceed = invocation.proceed();
                    } else {
                        proceed = invocation.proceed();
                        System.out.println("end");
                    }
                    return proceed;
                }
            });
            return factory.getProxy();
        } else {
            return bean;
        }
    }
}

